package edu.jxufe.nb112.common.web.support.captcha;

import com.octo.captcha.Captcha;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.captchastore.CaptchaAndLocale;
import com.octo.captcha.service.captchastore.CaptchaStore;
import edu.jxufe.nb112.common.code.cache.CacheService;

import java.util.Collection;
import java.util.Locale;

/**
 * Created by lvxi on 2018/4/8.
 * Note:
 */
public class CaptchaCacheStore  implements CaptchaStore {


    private CacheService cacheService;
    private String cacheName;

    public boolean hasCaptcha(String s) {
        return cacheService.getCache(cacheName).get(s)!=null;
    }

    public void storeAnswer(String s, String answer) throws CaptchaServiceException {
        cacheService.getCache(cacheName).put(s,answer);
    }
    public String getAnswer(String s) throws CaptchaServiceException {
        return (String) cacheService.get(cacheName,s);
    }
    public void storeCaptcha(String s, Captcha captcha) throws CaptchaServiceException {
        cacheService.getCache(cacheName).put(s,captcha);
    }

    public void storeCaptcha(String s, Captcha captcha, Locale locale) throws CaptchaServiceException {
        cacheService.getCache(cacheName).put(s,new CaptchaAndLocale(captcha,locale));
    }

    public boolean removeCaptcha(String s) {
        if(getCaptcha(s)!=null){
            cacheService.getCache(cacheName).evict(s);
            return true;
        }
        return false;
    }

    public boolean removeAnswer(String s) {
        if(getAnswer(s)!=null){
            cacheService.getCache(cacheName).evict(s);
            return true;
        }
        return false;
    }


    public Captcha getCaptcha(String s) throws CaptchaServiceException {
        CaptchaAndLocale captchaAndLocale =(CaptchaAndLocale) cacheService.get(cacheName,s);
        return  captchaAndLocale!=null?captchaAndLocale.getCaptcha():null;
    }

    public Locale getLocale(String s) throws CaptchaServiceException {
        CaptchaAndLocale captchaAndLocale =(CaptchaAndLocale) cacheService.get(cacheName,s);
        return captchaAndLocale!=null?captchaAndLocale.getLocale():null;
    }

    public int getSize() {
        return cacheService.size(cacheName);
    }

    public Collection getKeys() {
        return cacheService.keys(cacheName);
    }

    public void empty() {
         cacheService.clear(cacheName);
    }

    public void initAndStart() {

    }

    public void cleanAndShutdown() {
        cacheService.clear(cacheName);
    }

    public CacheService getCacheService() {
        return cacheService;
    }

    public void setCacheService(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    public String getCacheName() {
        return cacheName;
    }

    public void setCacheName(String cacheName) {
        this.cacheName = cacheName;
    }
}
